﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine.Types.ServerTasks;

namespace Pcm.Inventory.Client.FormTasks
{
    public partial class RE_Stock_Take : FormClientTask
    {
        #region Constants

        const string InventoryForSKUAndStorageLocationQueryName = "RE_Inventory for SKU? Storage Location?";
        const string StorageLocationIdFieldName = "Storage_Location_Id";
        const string ProductSKUIdFieldName = "Product_SKU_Id";
        const string ExistingQuantityFieldName = "Existing_Quantity";
        const string StockTakeQuantityFieldName = "Stock_Take_Quantity";
        const string QuantityActualFieldName = "Quantity_Actual";
        const string VarianceFieldName = "Variance";
        const string ProductId = "Product_Id";
        const string Status = "Status";
        const string REInventoryTable = "RE_Inventory";
        const string QuantityTheoreticalFieldName = "Quantity_Theoretical";
        const string stockDetailSecondary = "RE_Stock_Take_Detail_Stock_Take_Id";

        #endregion

        /// <summary>
        /// This Event is fired when Reconcile Button is clicked.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     06/01/2012      VT          Initial version.
        /// </history>
        public virtual void ReconcileButtonOnClick(object sender, EventArgs args)
        {
            try
            {
                this.Reconcile();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// This Event is fired when Process Button is clicked
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     06/01/2012      VT          Initial version.
        /// </history>
        public virtual void ProcessButtonOnClick(object sender, EventArgs args)
        {
            try
            {
                this.Reconcile();
                this.FormView.SaveRecord();
                this.SystemClient.ExecuteServerTask("RE_Stock_Take", "ProcessStock",
                                                new Type[] { typeof(object) },
                                                new object[] { this.RecordId.ToByteArray() });
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Barcode keyed in or populated after being scanned
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        /// </history>
        public virtual void OnDataSourceUpdatedBarcode(PivotalControl sender, EventArgs args)
        {
            try
            {
                BarcodeValueChanged();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// Barcode keyed in or populated after being scanned
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        /// </history>
        public virtual void Barcode_KeyPress(PivotalControl sender, KeyEventArgs args)
        {
            try
            {
                //If Enter key is hit
                if (args.KeyValue == 13)
                    this.FormControl.GetControlByDataName("Product_Id").Focus();
                //Don't worry abt the focus as it gets set again. This is just to naturally fire the datasourceupdated event.
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        /// </history>
        public virtual void Product_DataSourceUpdated(PivotalControl sender, EventArgs args)
        {
            try
            {
                CdcSoftware.Pivotal.Engine.UI.Forms.PivotalForeignKey fkProdSKU = this.FormControl.GetControlByName("ProductSKUId")
                    as CdcSoftware.Pivotal.Engine.UI.Forms.PivotalForeignKey;
                if (this.PrimaryDataRow["Product_Id"] != DBNull.Value)
                    fkProdSKU.ReadOnly = false;
                else
                    fkProdSKU.ReadOnly = true;
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product SKU field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        /// </history>
        public virtual void ProductSKU_DataSourceUpdated(PivotalControl sender, EventArgs args)
        {
            try
            {
                if (!Convert.IsDBNull(this.PrimaryDataRow["Product_SKU_Id"]))
                {
                    DataTable productSKU = Globals.GetDataTable("RE_Product_SKU", new List<NameValuePair>() { new NameValuePair("RE_Product_SKU_Id", 
                    Id.Create(this.PrimaryDataRow["Product_SKU_Id"])) });

                    if (productSKU != null && productSKU.Rows.Count > 0)
                    {
                        //Gee the produc tdetails and populate the secondary.
                        FetchProductSKU(productSKU);

                        //Reset the produc and sku fields.
                        this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                        this.PrimaryDataRow["Product_SKU_Id"] = DBNull.Value;
                        this.FormControl.GetControlByDataName("Product_Id").Focus();
                    }

                    //Set the Product SKU field to read-only again
                    if (this.PrimaryDataRow["Product_Id"] != DBNull.Value)
                        ((CdcSoftware.Pivotal.Engine.UI.Forms.PivotalForeignKey)this.FormControl.GetControlByName("ProductSKUId")).ReadOnly = false;
                    else
                        ((CdcSoftware.Pivotal.Engine.UI.Forms.PivotalForeignKey)this.FormControl.GetControlByName("ProductSKUId")).ReadOnly = true;
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }
    }
}
